<script setup lang="ts">
import { useComputeApp } from '@/hooks/web/useComputeApp'

defineOptions({
  name: 'Pagination'
})

const { layoutCurrentSize } = useComputeApp()
const isSmall = ref<boolean>(layoutCurrentSize.value === 'small')

watchEffect(() => {
  isSmall.value = layoutCurrentSize.value === 'small'
})

const props = defineProps({
  total: {
    required: true,
    type: Number
  },
  page: {
    type: Number,
    default: 1
  },
  limit: {
    type: Number,
    default: 20
  },
  pagerCount: {
    type: Number,
    default: document.body.clientWidth < 992 ? 5 : 7
  }
})

const emit = defineEmits(['update:page', 'update:limit', 'pagination'])
const currentPage = computed({
  get() {
    return props.page
  },
  set(val) {
    emit('update:page', val)
  }
})

const pageSize = computed({
  get() {
    return props.limit
  },
  set(val) {
    emit('update:limit', val)
  }
})

const handleSizeChange = (val: number) => {
  if (currentPage.value * val > props.total) {
    currentPage.value = 1
  }

  emit('pagination', { page: currentPage.value, limit: val })
}

const handleCurrentChange = (val: number) => {
  emit('pagination', { page: val, limit: pageSize })
}
</script>

<template>
  <el-pagination
    v-show="total > 0"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :background="true"
    :page-sizes="[10, 20, 30, 50, 100]"
    :pager-count="pagerCount"
    :total="total"
    :small="isSmall"
    class="float-right mb-15px mt-15px"
    layout="total, sizes, prev, pager, next, jumper"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>
